<template>
  <div>
    <el-row>
      <el-form ref="articleFormRef" :model="form" :rules="rules">
        <el-form-item hidden>
          <el-input v-model="form.articleId" hidden />
          <el-input v-model="form.status" hidden />
          <el-input v-model="form.thumbnail" hidden />
          <el-input v-model="form.source" hidden />
        </el-form-item>
        <el-col :span="24">
          <el-card shadow="always" class="m-b-10">
            <el-row :gutter="10">
              <el-col :span="16">
                <el-col :span="24">
                  <el-form-item prop="title">
                    <el-input v-model="form.title" placeholder="文章标题" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="summary">
                    <el-input
                      v-model="form.summary"
                      type="textarea"
                      placeholder="文章摘要"
                      :rows="2"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-row>
                    <el-form-item prop="channel">
                      <el-col :span="4">
                        <label>栏目</label>
                      </el-col>
                      <el-col :span="16">
                        <el-select v-model="form.channel" size="small">
                          <el-option
                            v-for="item in optionOfChannel"
                            :key="item.dictCode"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                          />
                        </el-select>
                      </el-col>
                    </el-form-item>
                  </el-row>
                </el-col>
                <el-col :span="12">
                  <el-row>
                    <el-form-item prop="direction">
                      <el-col :span="4">
                        <label>显示方向</label>
                      </el-col>
                      <el-col :span="8">
                        <el-select v-model="form.direction" size="small">
                          <el-option
                            v-for="item in optionOfDirection"
                            :key="item.dictCode"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                          />
                        </el-select>
                      </el-col>
                    </el-form-item>
                  </el-row>
                </el-col>
                <el-col :span="12">
                  <el-row>
                    <el-form-item prop="group">
                      <el-col :span="4">
                        <label>系列/主演</label>
                      </el-col>
                      <el-col :span="8" class="m-r-5">
                        <el-input v-model="form.group" size="small" @blur="handleNextGroupIndex" />
                      </el-col>
                      <el-col :span="1">
                        <el-input-number v-model="form.groupIndex" size="small" :min="1" />
                      </el-col>
                    </el-form-item>
                  </el-row>
                </el-col>
                <el-col :span="12">
                  <el-row>
                    <el-form-item prop="weight">
                      <el-col :span="4">
                        <label>排序</label>
                      </el-col>
                      <el-col :span="8">
                        <el-input-number v-model="form.weight" size="small" :min="1" />
                      </el-col>
                    </el-form-item>
                  </el-row>
                </el-col>
              </el-col>
              <el-col :span="8">
                <el-image style="height:240px;float:right;border: double" :src="getImageSrc(form.thumbnail)" alt="点击更换图片" fit="fill" @click="changeThumbnail">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline" @click="changeThumbnail" />
                  </div>
                </el-image>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="24">
          <el-card shadow="always" class="m-b-10">
            <el-form-item>
              <span class="m-r-10">编辑器</span>
              <el-radio v-model="form.editor" label="tinymce">Tinymce</el-radio>
              <el-radio v-model="form.editor" label="markdown">Markdown</el-radio>
            </el-form-item>
            <el-row>
              <tinymce-editor v-if="form.editor === 'tinymce'" ref="tinymce" v-model="form.content" :content="form.content" :height="400" @input="renderHtml" @close="onClose" />
              <markdown-editor v-if="form.editor === 'markdown'" ref="markdown" v-model="form.content" :content="form.content" @render="renderHtml" />
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="24">
          <el-card shadow="always">
            <el-row :gutter="10">
              <el-col :span="24" class="m-t-10 m-r-10">
                <el-form-item for="inputTagValue">
                  <label class="m-r-10">标签</label>
                  <el-tag
                    v-for="tag in optionOfTag"
                    :key="tag"
                    closable
                    :disable-transitions="false"
                    size="small"
                    class="m-l-5"
                    @close="handleTagDelete(tag)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    v-if="inputTagVisible"
                    ref="saveTagInput"
                    v-model="inputTagValue"
                    size="small"
                    class="input-new-tag"
                    @keyup.enter.native="handleTagConfirm"
                    @blur="handleTagConfirm"
                  />
                  <el-button v-if="!inputTagVisible" size="small" class="button-new-tag" icon="el-icon-plus" @click="handleAddTag" />
                </el-form-item>
              </el-col>
              <el-col :span="1.5" class="m-t-10">
                <el-form-item for="open">
                  <label class="m-r-10">权限</label>
                  <el-radio v-for="item in optionOfPermission" :key="item.dictCode" v-model="form.open" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="1.5" class="m-t-5">
                <el-form-item for="memberGrowth">
                  <label class="m-r-10 m-l-20">访问等级</label>
                  <el-select v-model="form.memberGrowth" size="small">
                    <el-option
                      v-for="item in optionOfMemberGrowth"
                      :key="'member_growth_' + item.id"
                      :label="item.name"
                      :value="item.growthPoint"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="1.5" class="m-t-10">
                <el-form-item for="crypto">
                  <label class="m-r-10 m-l-20">是否加密</label>
                  <el-radio v-for="item in optionOfCrypto" :key="item.dictCode" v-model="form.crypto" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                </el-form-item>
              </el-col>
              <el-col v-if="form.crypto === '0'" :span="1.5" class="m-t-10">
                <el-form-item for="crypto">
                  <label class="m-r-10 m-l-20">分享码</label>
                  <el-input v-model="form.salt" size="small" placeholder="请输入分享码" />
                </el-form-item>
              </el-col>
              <el-col :span="1.5" class="m-t-10 m-r-20 fr">
                <el-tag type="success" class="m-r-10">⋅ 阅读 {{ form.views }} ⋅</el-tag>
                <el-tag type="success" class="m-r-10">⋅ 收藏 {{ form.favors }} ⋅</el-tag>
                <el-tag type="success">⋅ 评论 {{ form.views }} ⋅</el-tag>
              </el-col>
            </el-row>
            <el-row type="flex" justify="center" class="m-b-10">
              <el-col :span="10">
                <el-input v-model="video_url" size="small" placeholder="URL地址转码" />
              </el-col>
              <el-col :span="2" style="text-align: center;">
                <el-button type="primary" size="small" icon="el-icon-refresh" circle @click="translateURL" />
              </el-col>
              <el-col :span="10">
                <el-input v-model="video_url_encode" size="small" placeholder="转码后URL地址" />
              </el-col>
            </el-row>
            <el-row class="m-t-20" type="flex" justify="center">
              <el-button v-if="form.title" type="warning" @click="onSubmit('2')">草 稿</el-button>
              <el-button v-if="form.title" class="m-l-20" type="primary" @click="onSubmit('0')">发布并关闭</el-button>
              <el-button v-if="!form.title" type="warning" @click="onClose()">关闭</el-button>
              <el-button v-if="form.articleId" class="m-l-20" type="danger" @click="onSubmit('1')">删 除</el-button>
            </el-row>
          </el-card>
        </el-col>
      </el-form>
    </el-row>

    <el-dialog title="文章缩略图" :modal="false" :visible.sync="openThumbnailDialog">
      <image-cropper ref="thumbnailCrop" :fixed-size="false" :upload-url="uploadThumbnailFinal" @onSuccess="setThumbnail" />
    </el-dialog>
  </div>
</template>

<script>
import { blogLoad, blogSave, blogNextIndex } from '@/api/blog/blog'
import { memberLevelList } from '@/api/system/member'
import Auth from '@/utils/auth'

export default {
  name: 'ArticleForm',
  data() {
    return {
      redirect: undefined,
      form: {
        articleId: undefined,
        status: undefined,
        thumbnail: '',
        source: 'manual',
        title: undefined,
        summary: undefined,
        editor: 'markdown',
        content: undefined,
        html: undefined,
        open: '0',
        crypto: '1',
        memberGrowth: 0,
        salt: undefined,
        weight: 0,
        channel: undefined,
        direction: undefined,
        tags: '',
        views: 0,
        favors: 0,
        comments: 0,
        group: undefined,
        groupIndex: undefined
      },
      uploadThumbnailFinal: `${process.env.VUE_APP_MODULE_VLOG_API}/api/blog/manage/uploadThumbnailFinal`,
      video_url: '',
      video_url_encode: '',
      rules: {
        title: [{ required: true, message: '请填写标题' }],
        channel: [{ required: true, message: '请选择栏目' }]
      },
      optionOfPermission: [],
      optionOfMemberGrowth: [],
      optionOfChannel: [],
      optionOfDirection: [],
      optionOfTag: [],
      optionOfCrypto: [],
      inputTagValue: undefined,
      inputTagVisible: false,
      openThumbnailDialog: false
    }
  },
  watch: {
    optionOfTag(value) {
      this.form.tags = this.optionOfTag.join(',')
    }
  },
  methods: {
    init(articleId) {
      // 加载下拉菜单
      this.getDictData()
      if (articleId) {
        this.form.articleId = articleId
      }
      this.$nextTick(() => {
        // 加载表单数据
        this.loadForm()
      })
    },
    getDictData() {
      const that = this
      this.$http.all([this.$dictGroup('blog_article_open'),
        memberLevelList(),
        this.$dictGroup('sys_yes_no'),
        this.$dictGroup('blog_article_channel'),
        this.$dictGroup('blog_article_direction'),
      ]).then(this.$http.spread(function(permission, growth, crypto, channel, direction) {
        that.optionOfPermission = permission
        that.optionOfMemberGrowth = growth
        that.optionOfCrypto = crypto
        that.optionOfChannel = channel
        that.optionOfDirection = direction
      }))
    },
    getImageSrc(value) {
      return this.$api.getImageSrc(value)
    },
    loadForm() {
      // 加载tinymce插件
      if (this.form.editor === 'tinymce') {
        this.$refs.tinymce.update('')
      }
      if (this.form.articleId) {
        blogLoad({ 'id': this.form.articleId }).then(response => {
          this.form = this.$api.objectUpdate(this.form, response.param)
          if (this.form.tags) {
            this.optionOfTag = this.form.tags.split(',')
          }
          this.$refs.tinymce.update(this.form.content)
        }).catch(() => {})
      }
    },
    handleNextGroupIndex() {
      if (this.form.group) {
        blogNextIndex({'group': this.form.group}).then(response => {
          this.form.groupIndex = response.param
        }).catch(() => {})
      }
    },
    changeEditor() {
      if (this.form.editor === 'tinymce') {
        this.$refs.tinymce.update('')
        this.$refs.tinymce.update(this.form.content)
      }
    },
    changeThumbnail() {
      this.openThumbnailDialog = true
      this.$nextTick(() => {
        let avatarUrl
        if (this.form.thumbnail) {
          avatarUrl = this.$store.getters.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/public/file/preview/` + this.form.thumbnail
        } else {
          avatarUrl = ''
        }
        this.$refs.thumbnailCrop.init(avatarUrl)
      })
    },
    setThumbnail(avatarId) {
      this.form.thumbnail = avatarId
      this.openThumbnailDialog = false
    },
    translateURL() {
      if (this.video_url) {
        this.video_url_encode = encodeURI(this.video_url)
      }
    },
    handleAddTag() {
      this.inputTagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleTagConfirm() {
      const inputValue = this.inputTagValue
      if (inputValue) {
        this.optionOfTag.push(inputValue)
      }
      this.inputTagVisible = false
      this.inputTagValue = ''
    },
    handleTagDelete(tag) {
      this.optionOfTag.splice(this.optionOfTag.indexOf(tag), 1)
    },
    renderHtml(render) {
      this.form.html = render
    },
    onSubmit(type) {
      // eslint-disable-next-line no-unused-vars
      let close = false
      if (type === '0' || type === '1') {
        close = true
      }

      if (!this.form.content) {
        this.$modal.msgWarning('请输入文章内容')
        return false
      }

      this.form.status = type
      // 判断是否加密
      if (this.form.crypto === '0') {
        if (!this.form.salt) {
          this.$modal.msgWarning('请输入分享码')
          return false
        }
        this.form.content = Auth.Encrypt(this.form.content)
        this.form.html = Auth.Encrypt(this.form.html)
        if (this.form.summary) {
          this.form.summary = Auth.Encrypt(this.form.summary)
        }
      }

      this.$refs.articleFormRef.validate(valid => {
        if (valid) {
          blogSave(this.form).then(response => {
            this.$modal.msgSuccess(response.msg)
            if (close) {
              this.onClose()
              this.$emit('close')
            }
          }).catch(() => {})
        } else {
          return false
        }
      })
    },
    onClose() {
      if (this.form.editor === 'tinymce') {
        this.$refs.tinymce.update('')
      }
      this.form = {
        articleId: undefined,
        status: undefined,
        thumbnail: '',
        source: 'manual',
        title: undefined,
        summary: undefined,
        editor: 'tinymce',
        content: undefined,
        html: undefined,
        open: '0',
        crypto: '1',
        memberGrowth: 0,
        salt: undefined,
        weight: 0,
        channel: undefined,
        direction: undefined,
        tags: '',
        views: 0,
        favors: 0,
        comments: 0,
        group: undefined,
        groupIndex: undefined
      }

      this.video_url = ''
      this.video_url_encode = ''
      this.optionOfTag = []
      this.inputTagValue = undefined
      this.inputTagVisible = false
      this.openThumbnailDialog = false
    }
  }
}
</script>
